<?php
namespace Home\Controller;

use Think\Controller;

class PayController extends CommonController{

    public function index(){

    header("Content-type:text/html;charset=utf-8");
        //读取商户配置
        $merchant = C('MERCHANT');
        $payserverUrl = C('PAYSERVERURL');
        $key = C('KEY');
        $callBack = C('CALLBACK');
        $returnURL = C('RETURNURL');

        $module = 2;//h5支付类型
        $payer = 'alipay'; //$_GET['payer'];
        $module_array = array("1", "2");
        if (in_array($module, $module_array) == false) exit;
        $pay_array = array(
            'alipay' => "ali",
            'wxpay' => "weixin",
            'qqpay' => "qq"
        );
        if (array_key_exists($payer, $pay_array) == false) exit;
        $module = (int)$module;
        $payname_array = array(
            'alipay' => "支付宝",
            'wxpay' => "微信",
            'qqpay' => "QQ"
        );

        $username =I('POST.username');
        $uid = intval(I('POST.uid'));
        $payamount = sprintf("%.2f", I('POST.amount'));
        if ($payamount <= 0) {
            exit;
        }

        $sn = getsn($merchant);

        $deviceInfo = $uid;
        $totalAmount = $payamount;
        $subject = "用户名 " . $username . " " . $payname_array[$payer] . "充值 " . $totalAmount . " 元";
        $tradeIP = get_ip();
        $remark = $subject;
        $channel = $pay_array[$payer];
        $terminalType = "mobile";

        if ($module == 2) {

            $busiType = '120001';
            $content = $sn.$merchant.$deviceInfo.$totalAmount.$subject.$callBack.$returnURL.$channel.$terminalType.$tradeIP.$remark.$key;
           // echo 'md5 sign content:'.$content.'</br>';exit;
            $sign_md5 = md5($content);

            $sign = sign_sha1($sign_md5);
           //echo 'sha1 sign content:'.$sign.'</br>'; //sign value

            $keyStr16 = generate_randsn(16);
           // echo 'keyStr16:'.$keyStr16.'</br>';

            //$busiType='120001';
            $aes_content = $sign_md5.$busiType;
           // echo 'aes_content:'.$aes_content.'</br>';

            $encryptData = sign_aes($aes_content,$keyStr16);
           // echo 'encryptData:'.$encryptData.'</br>';//encryptData value


            $encryptKey = sign_rsa($keyStr16);
           // echo 'encryptKey:'.$encryptKey.'</br>'; //encryptKey value

           // echo urlencode($sign).'</br>';
           // echo urlencode($encryptData).'</br>';
           // echo urlencode($encryptKey).'</br>';exit;

            //post方式
            $curlPost = 'merchant='.$merchant.'&sn='.$sn.'&deviceInfo='.$deviceInfo.'&totalAmount='.$totalAmount.'&subject='.$subject.'&returnURL='.$returnURL.'&callBack='.$callBack.'&channel='.$channel.'&busiType='.$busiType.'&terminalType='.$terminalType.'&tradeIP='.$tradeIP.'&remark='.$remark.'&sign='.urlencode($sign).'&encryptData='.urlencode($encryptData).'&encryptKey='.urlencode($encryptKey);
           // echo $curlPost;exit;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $payserverUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);//单位 秒，也可以使用
        //设置是通过post还是get方法
        curl_setopt($ch, CURLOPT_POST, 1);
        //传递的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); // 请求返回值
        curl_close($ch);
        //echo 'Req Data:'.$data.'</br>';exit;
        $dataJson = json_decode($data);
        $codeRsp = $dataJson->codeRsp;
        $codeRsp = json_encode($codeRsp);
        $encrypt = $dataJson->encrypt;
        $codeRsp = json_decode($codeRsp, true);  //再把json字符串格式化为数组
         echo 'codeRsp:' . json_encode($codeRsp) . '</br>';exit;
        // echo var_dump($codeRsp).'</br>';
        //echo $codeRsp["aliPayURL"];//获取H5支付URL
        //echo $codeRsp["qrCode"];exit; //获取扫码支付URL

        if ($module == 2) {
            //echo "<BR><BR>".$codeRsp["aliPayURL"];exit;
            if (empty($codeRsp["aliPayURL"])) {
                $tip="支付通道繁忙，请重新提交充值!";
                echo "<script language=\"javaScript\">alert(\"$tip\");window.close();</script>";
            }
               header("Location: ".$codeRsp["aliPayURL"]);
        }

         //encrypt值可能为空
        if ($encrypt) {
            $en_encryptKey = $encrypt->encryptKey;
            $en_encryptData = $encrypt->encryptData;
            //echo 'en_encryptKey:'.$en_encryptKey.'</br>';
            //echo 'en_encryptData:'.$en_encryptData.'</br>';

            $deKeyStr16 = decode_rsa(urldecode($en_encryptKey));
            //echo '</br>'.'deKeyStr16:'.$deKeyStr16.'</br>';

            $deData = decode_aes($deKeyStr16, urldecode($en_encryptData));
            //echo 'deData:'.$deData.'</br>';

            //echo "--:".substr($deData,0,strrpos($deData,'}')+1);
            $dataJsonRs = json_decode(substr($deData, 0, strrpos($deData, '}') + 1));
            //echo 'code:'.$dataJsonRs->code.'</br>';
        }
    }

   public function callback(){

       //读取商户配置
       $merchant = C('MERCHANT');
       $key = C('KEY');
       $param = array (
           'encryptData' => $_POST["encryptData"],
           'sign' => $_POST["sign"],
           'responeSN' => $_POST["responeSN"],
           'message' => $_POST["message"],
           'encryptKey' => $_POST["encryptKey"],
       );

       $responeSN = $param['responeSN'];
       $message = $param['message'];
       $data = $responeSN.$merchant.$message.$key;
       //printf('%s</br>',$data);
       $sign_md5 = md5($data);
       //printf('%s</br>',$sign_md5);
        //printf('%s</br>',urldecode($param['sign']));

       $isOK = sign_verify($sign_md5,urldecode($param['sign']));
       //printf('%s</br>',$isOK);

       /*$en_encryptKey = $param['encryptKey'];
       $en_encryptData = $param['encryptData'];
       $deKeyStr16 = decode_rsa(urldecode($en_encryptKey));
       $deData = decode_aes($deKeyStr16,urldecode($en_encryptData));
       $dataJsonRs = json_decode(substr($deData,0,strrpos($deData,'}')+1));
       //printf('%s</br>',$deKeyStr16);
       //printf('%s</br>',$deData);
       //printf('%s</br>',$dataJsonRs);*/

       if($isOK==1){ //支付成功业务处理
           echo "0000";
           $message = json_decode($message,true);
           if($message["code"]=="0000"){
               $user_id = $message["deviceInfo"];
               $order_num = $message["responeSN"];
               $order_value = $message["payAmount"];
               $pay_name = "H5支付";
               $remark = $message['remark'];
               $signInfo = $param['message'];
               //printf('%s</br>',$signInfo);
               //Manipulatemoney($user_id,$order_num,$order_value,$pay_name,$remark,$signInfo);
           }
       }

   }

   public function returnURL(){

       //读取商户配置
       $merchant = C('MERCHANT');

       $param = array (
           'encryptData' => $_POST["encryptData"],
           'sign' => $_POST["sign"],
           'responeSN' => $_POST["responeSN"],
           'message' => $_POST["message"],
           'encryptKey' => $_POST["encryptKey"],
       );

       $responeSN = $param['responeSN'];
       $message = $param['message'];
       $data = $responeSN.$merchant.$message. C('KEY');;
       //printf('%s</br>',$data);

       $sign_md5 = md5($data);
       //printf('%s</br>',$sign_md5);
       //printf('%s</br>',urldecode($param['sign']));

       $isOK = sign_verify($sign_md5,urldecode($param['sign']));
       //printf('%s</br>',$isOK);

       /*$en_encryptKey = $param['encryptKey'];
       $en_encryptData = $param['encryptData'];
       $deKeyStr16 = decode_rsa(urldecode($en_encryptKey));
       $deData = decode_aes($deKeyStr16,urldecode($en_encryptData));
       $dataJsonRs = json_decode(substr($deData,0,strrpos($deData,'}')+1));
       //printf('%s</br>',$deKeyStr16);
       //printf('%s</br>',$deData);
       //printf('%s</br>',$dataJsonRs);*/

       if(1){ //支付成功业务处理
           $message = json_decode($message,true);
           if($message["code"]=="0000"){
               $user_id = $message["deviceInfo"];
               $order_num = $message["responeSN"];
               $order_value = $message["payAmount"];
               $pay_name = "H5支付";
               $remark = $message['remark'];
               $signInfo = $param['message'];
               //printf('%s</br>',$signInfo);

               //Manipulatemoney($user_id,$order_num,$order_value,$pay_name,$remark,$signInfo);
               echo "<script language=\"javaScript\">alert(\"在线支付成功！\");window.close();</script>";
           }
       }
   }

}